﻿using AutoMapper;
using MediatR;
using SU.Center.Domain.RBAC;
using SU.Center.Infa;
using System.Transactions;

namespace SU.Center.Api.Handler.RBAC
{
    /// <summary>
    /// 删除用户信息
    /// </summary>
    public class DeleteUserInfoHandler : IRequestHandler<DeleteUserInfoRepsultDto, ApiResult>
    {
        private readonly IBaseReposiotry<UserInfo> baseReposiotry;
        private readonly IBaseReposiotry<UserRoles> reposiotry;
        private readonly ILogger<DeleteUserInfoHandler> logger;
        private readonly IMapper mapper;

        public DeleteUserInfoHandler(IBaseReposiotry<UserInfo> baseReposiotry, IBaseReposiotry<UserRoles> reposiotry, ILogger<DeleteUserInfoHandler> logger, IMapper mapper)
        {
            this.baseReposiotry = baseReposiotry;
            this.reposiotry = reposiotry;
            this.logger = logger;
            this.mapper = mapper;
        }

        public async Task<ApiResult> Handle(DeleteUserInfoRepsultDto request, CancellationToken cancellationToken)
        {
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var user = await baseReposiotry.GetAsync(x => x.UserInfoId == request.UserInfoId);
                    await baseReposiotry.DeleteEntity(user);
                    var list = await reposiotry.GetsAll(x => x.UserInfoId == request.UserInfoId);

                    await reposiotry.DeleteRangeEntity(list);
                    tran.Complete();
                    return ApiResult.Ok();
                }
                finally
                {
                    tran.Dispose();
                }
               
            }
        }
    }
}
public class DeleteUserInfoRepsultDto : IRequest<ApiResult>
{
    public int UserInfoId { get; set; }
}
